﻿using System.Configuration;
using System.Xml;

namespace Cache.MemoryCache
{
    public class MemoryCachedSection
    {
        public static MemoryCachedConfig GetConfig()
        {
            var section = ConfigurationManager.GetSection("Cache") as XmlNode;
            if (section == null)
            {
                return null;
            }
            foreach (XmlNode child in section.ChildNodes)
            {
                if (child.Name.ToLower() == "memorycached")
                {
                    return ParseConfig(child);
                }
            }
            return null;
        }

        private static MemoryCachedConfig ParseConfig(XmlNode section)
        {
            var config = new MemoryCachedConfig();
            foreach (XmlNode child in section.ChildNodes)
            {
                if (child.Name.ToLower() == "setting")
                {
                    if (child.Attributes["IsCache"] != null)
                    {
                        config.IsCache = bool.Parse(child.Attributes["IsCache"].Value);
                    }
                    if (child.Attributes["IntervalMinutes"] != null)
                    {
                        config.IntervalMinutes = int.Parse(child.Attributes["IntervalMinutes"].Value);
                    }
                    if (child.Attributes["ScavangeMinutes"] != null)
                    {
                        config.ScavangeMinutes = int.Parse(child.Attributes["ScavangeMinutes"].Value);
                    }
                    if (child.Attributes["MaxCount"] != null)
                    {
                        config.MaxCount = long.Parse(child.Attributes["MaxCount"].Value);
                    }
                    if (child.Attributes["MaxSize"] != null)
                    {
                        string[] maxSizes = child.Attributes["MaxSize"].Value.Split('*');
                        config.MaxSize = 1;
                        foreach (string item in maxSizes)
                        {
                            config.MaxSize *= long.Parse(item);
                        }

                        //config.MaxSize = long.Parse(child.Attributes["MaxSize"].Value);
                    }
                }
                else if (child.Name.ToLower() == "add")
                {
                    var node = new MemoryCachedNode();
                    if (child.Attributes["name"] != null)
                    {
                        node.Name = child.Attributes["name"].Value;
                    }

                    if (child.Attributes["KeyPrefix"] != null)
                    {
                        node.KeyPrefix = child.Attributes["KeyPrefix"].Value;
                    }
                    config.Nodes.Add(node.Name, node);
                }
            }
            return config;
        }
    }
}